package cn.itcast.musicplayer;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 本服务提供音乐播放功能，对外需要提供，开始播放，暂停播放，继续播放，设置音乐播放位置，及进度信息。
 */
public class MusicService extends Service {
    private MediaPlayer player;
    private Timer timer;

    public MusicService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
    }

    @Override
    public IBinder onBind(Intent intent) {
        MusicControl musicContro = new MusicControl();
        return musicContro;
    }

    /**
     * TODO 播放的时候，将会开启一个定时器，周期性的发送进度信息
     * 给 MainActivity，用来更新界面
     */

    public void addTimer(){
        if(timer==null){
            timer = new Timer();
        }
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if(player == null){
                    return;
                }
                int duration = player.getDuration();
                int currentPosition = player.getCurrentPosition();
                Message message = MainActivity.handler.obtainMessage();
                Bundle bundle = new Bundle();
                bundle.putInt("duration",duration);
                bundle.putInt("currentPosition",currentPosition);
                message.setData(bundle);
                MainActivity.handler.sendMessage(message);
            }
        };
        timer.schedule(timerTask,5,500);
    }

    public class MusicControl extends Binder {
        public void play() {
            player.reset();
            player = MediaPlayer.create(getApplicationContext(), R.raw.music);
            player.start();
            addTimer();
        }

        public void pausePlay() {
            if (player != null) {
                player.pause();
            }
        }

        public void continuePlay() {
            if (player != null) {
                player.start();
            }
        }

        public void seekTo(int progress) {
            if (player != null) {
                player.seekTo(progress);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player == null) return;
        if (player.isPlaying()) player.stop();
        player.release();
        player = null;
    }
}
